/**
 * Copyright 2018 人人开源 http://www.renren.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package io.renren.service.impl;


import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.renren.bean.StudentInfo;
import io.renren.common.exception.RRException;
import io.renren.common.utils.R;
import io.renren.dao.StudentDao;
import io.renren.entity.SmsLogEntity;
import io.renren.entity.StudentEntity;
import io.renren.entity.TokenEntity;
import io.renren.service.SchoolService;
import io.renren.service.SmsLogService;
import io.renren.service.StudentService;
import io.renren.service.TokenService;
import io.renren.util.StringUtils;
import io.renren.util.ValidateUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service("studentService")
public class StudentServiceImpl extends ServiceImpl<StudentDao, StudentEntity> implements StudentService {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private SmsLogService smsLogService;
    @Autowired
    private SchoolService schoolService;


    /***
     * 登录
     * 账号可以是手机号或者身份证
     * @param account 账号(手机或身份证)
     * @param password 密码
     * @return
     */
    @Override
    public Map<String, Object> login(@Param("account") String account,
                                     @Param("password") String password) {

        StudentEntity user = queryByAccount(account);
        if (user == null) {
            return R.fail("用户名或者密码错误");
        }

        //密码错误
        if (!user.getPassword().equals(DigestUtils.sha256Hex(password))) {
            throw new RRException("用户名或者密码错误");
        }
        //查看用户是否被禁用或删除
        Integer i = null;
        if (user.getState() != null) {
            i = Integer.valueOf(user.getState());
            if (i != 1) {
                throw new RRException("该账号被禁用或者被删除");
            }
        }
        user.setLoginCount(user.getLoginCount() + 1);
        //获取登录token
        TokenEntity tokenEntity = tokenService.createToken(user.getUserId());
        Map<String, Object> map = new HashMap<>(2);
        map.put("token", tokenEntity.getToken());
        map.put("expire", tokenEntity.getExpireTime().getTime());
        map.put("studentName", user.getRealname());
        map.put("studentId", user.getUserId());
        studentService.updateById(user);
        return map;
    }

    /***
     * 小程序
     * 登录(手机号码+验证码)
     * @param phone 手机
     * @Param smsCode 验证码
     * @return
     */
    @Override
    public Map<String, Object> XLogin(String phone, String smsCode) {
        if (!Validator.isMobile(phone)) {
            return R.fail("请输入正确的手机号码");
        }
        StudentEntity user = queryByAccount(phone);
        if (user == null) {
            user = new StudentEntity();
            user.setUsername(null);
            user.setSex(3);
            user.setImgUrl("http://pic.nataliee.top/default_avatar.jpg");
            user.setMobile(phone);
            user.setLoginCount(0);
            user.setCreateTime(new Date());
            user.setState(1);
            user.setPassword("123456");
            studentService.insert(user);
        }
        SmsLogEntity smsLog = smsLogService.querySmsCodeByPhone(phone);
        if (Validator.isEmpty(smsLog)) {
            return R.fail("请先获取验证码");
        }
        //有效期5分钟
        if ((System.currentTimeMillis() / 1000 - smsLog.getLogDate()) > 5 * 60) {
            return R.fail("验证码已过期");
        }
        if (!smsCode.equals(smsLog.getSmsCode())) {
            return R.fail("验证码错误");
        }
        //查看用户是否被禁用或删除
        Integer i = null;
        if (user.getState() != null) {
            i = Integer.valueOf(user.getState());
            if (i != 1) {
                throw new RRException("该账号被禁用或者被删除");
            }
        }
        user.setLoginCount(user.getLoginCount() + 1);
        //获取登录token
        TokenEntity tokenEntity = tokenService.createToken(user.getUserId());
        Map<String, Object> map = new HashMap<>(2);
        map.put("token", tokenEntity.getToken());
        map.put("expire", tokenEntity.getExpireTime().getTime());
        map.put("studentName", user.getRealname());
        map.put("studentId", user.getUserId());
        studentService.updateById(user);
        return map;
    }

    /***
     * 退出登录
     * @param student 学生
     * @return
     */
    @Override
    public R logout(StudentEntity student) {
        tokenService.deleteToken(student.getUserId());
        return R.ok("退出成功");
    }

    /***
     * 获取关联学校
     * @param student 学生
     * @return
     */
    @Override
    public R getRelatedSchool(StudentEntity student) {
        Integer schoolId = student.getSchoolId();
        if (schoolId == null) {
            return R.fail("没有关联学校");
        }
        //获取学校名称
        Map<String, Object> getSchool = schoolService.getSchoolName(schoolId);
        return R.ok(getSchool);
    }


    /**
     * 使用手机或者身份证号码作为账号
     *
     * @param account 账号(手机,身份证)
     */
    private StudentEntity queryByAccount(String account) {
        StudentEntity studentEntity = this.baseMapper.getLoginStudent(account);
        return studentEntity;
    }

    @Override
    public Page getListbyPage() {
        return this.selectPage(new Page<>(1, 10), new EntityWrapper<StudentEntity>().like("mobile", "136"));
    }

    /**
     * 获取学员信息
     *
     * @param student 学员
     * @return R
     */
    @Override
    public R getStudentInfo(StudentEntity student) {
        StudentInfo studentInfo = new StudentInfo();
        //获取学员信息
        Map<String, Object> studentMap = baseMapper.getStudentMap(student.getUserId());
        if (studentMap != null && studentMap.size() > 0) {
            String studentName = studentMap.get("realname") == null ? "" : studentMap.get("realname").toString();
            String mobile = studentMap.get("mobile") == null ? "" : studentMap.get("mobile").toString();
            String idCard = studentMap.get("idCard") == null ? "" : studentMap.get("idCard").toString();
            String sex = studentMap.get("sex") == null ? "" : studentMap.get("sex").toString();
            String loginCount = studentMap.get("loginCount") == null ? "" : studentMap.get("loginCount").toString();
            String schoolName = studentMap.get("schoolName") == null ? "" : studentMap.get("schoolName").toString();
            //学校名称
            studentInfo.setSchoolName(schoolName);
            //身份证
            studentInfo.setIdCard(idCard);
            //性别 1男2女3保密
            studentInfo.setSex(sex);
            //学生名称
            studentInfo.setStudentName(studentName);
            //手机号
            studentInfo.setMobile(mobile);
            //登录次数
            studentInfo.setLoginCount(loginCount);
        }
        //获取该学员的科目
        List<Map<String, Object>> subjectList = baseMapper.getSubjectList(student.getUserId());
        if (subjectList != null && subjectList.size() > 0) {
            List<StudentInfo.Subject> signUpSubjectList = new ArrayList<StudentInfo.Subject>();
            for (int i = 0; i < subjectList.size(); i++) {
                StudentInfo.Subject subject = studentInfo.new Subject();
                String subjectName = subjectList.get(i).get("subjectName") == null ? "" : subjectList.get(i).get("subjectName").toString();
                subject.setSubjectName(subjectName);
                signUpSubjectList.add(subject);
            }
            studentInfo.setSubjectNameList(signUpSubjectList);

        }
        return R.ok(studentInfo);
    }

    /***
     * 获取学校信息
     * @param schoolId 学校id
     * @return R
     */
    @Override
    public R getSchoolInfo(Integer schoolId) {
        Map<String, Object> schoolInfo = baseMapper.getSchoolInfo(schoolId);
        return R.ok(schoolInfo);
    }

    /**
     * 获取学校列表
     *
     * @return R
     */
    @Override
    public R getSchoolList() {
        List<Map<String, Object>> getSchoolList = baseMapper.getSchoolList();
        return R.ok(getSchoolList);
    }

    /***
     *小程序
     * 获取一键报名科目id
     * @param type 科目类别:1人社 2交通 3安监
     * @param subjectName 科目名称
     * @return
     */
    @Override
    public R getSignUpSubjectId(Integer type, String subjectName) {
        List<Map<String, Object>> signUpSubjectList = baseMapper.getSignUpSubjectList(type, subjectName);
        return R.ok(signUpSubjectList);
    }

    /**
     * 小程序
     * 一键报名
     *
     * @param realName  真实姓名
     * @param phone     手机号码
     * @param idCard    身份证
     * @param subjectId 科目id
     * @return R
     */
    @Override
    public R signUpRecord(String realName, String phone, String idCard, Integer subjectId) {
        if (!ValidateUtils.isMobile(phone)) {
            return R.fail("手机号码格式不正确");
        }
        if (!ValidateUtils.isIdNo(idCard)) {
            return R.fail("身份证格式不正确");
        }
        String subjectName = baseMapper.getSubjectName(subjectId);
        //新增信息
        baseMapper.insertSignUpRecord(realName, phone, idCard, subjectId, subjectName);
        return R.ok();
    }


    /***
     * 小程序
     * 获取证件信息
     * @param student 学员
     * @return
     */
    @Override
    public R getCertificate(StudentEntity student) {
        List<Map<String, Object>> certificate = baseMapper.getCertificate(student.getUserId(), student.getSchoolId());
        return R.ok(certificate);
    }

    /***
     * 小程序
     * 修改个人中心
     * @param student 学员
     * @param imgUrl 头像
     * @param realName 真实姓名
     * @param phone 电话
     * @param idCard 身份证
     * @param userName 昵称
     * @param sex 性别 1男 2女 3保密
     * @return
     */
    @Override
    public R setCenterInfo(StudentEntity student, String imgUrl, String realName, String phone, String idCard, String userName, Integer sex) {
        if (StringUtils.isNotBlank(imgUrl)) {
            student.setImgUrl(imgUrl);
        }
        if (StringUtils.isNotBlank(realName)) {
            student.setRealname(realName);
        }
        if (StringUtils.isNotBlank(phone)) {
            if (!ValidateUtils.isMobile(phone)) {
                return R.fail("手机号格式不正确");
            } else {
                student.setMobile(phone);
            }
        }
        if (StringUtils.isNotBlank(idCard)) {
            if (!ValidateUtils.isIdNo(idCard)) {
                return R.fail("身份证号格式不正确");
            } else {
                student.setIdCard(idCard);
            }
        }
        if (StringUtils.isNotBlank(userName)) {
            student.setUsername(userName);
        }
        if (sex != null) {
            student.setSex(sex);
        }
        studentService.updateById(student);
        return R.ok(student);
    }

    /***
     * 小程序
     * 获取我的订单
     * @param student 学员
     * @return R
     */
    @Override
    public R getOrderList(StudentEntity student) {
        //获取订单列表
        List<Map<String, Object>> orderList = baseMapper.getOrderList(student.getUserId());
        return R.ok(orderList);
    }

    /***
     * 小程序
     * 获取个人中心信息
     * @param student
     * @return R
     */
    @Override
    public R getCenterInfo(StudentEntity student) {
        Map<String, Object> centerInfo = baseMapper.getCenterInfo(student.getUserId());
        return R.ok(centerInfo);
    }


}
